import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchWeather } from '../actions/weather';

class SearchBar extends Component {
  constructor(props) {
    super(props);

    this.state = {
      term: 'Beijing'
    };

    this.onInputChange = this.onInputChange.bind(this);
    this.onFormSubmit = this.onFormSubmit.bind(this);
    this.props.fetchWeather(this.state.term);
  }

  onInputChange(event) {
    // console.log(event.target.value)
    this.setState({
      term: event.target.value
    });
  }

  onFormSubmit(event) {
    event.preventDefault();
    // we need to go and fetch weather data
    this.props.fetchWeather(this.state.term);
    this.setState({
      term: ''
    });
  }
  render() {
    return (
      <form
        onSubmit={this.onFormSubmit}
        className="input-group"
      >
        <input
          placeholder="输入城市名"
          className="form-control"
          value={this.state.term}
          onChange={this.onInputChange}
        />
        <span className="input-group-btn">
          <button type="submit" className="btn btn-secondary">
            搜索
          </button>
        </span>
      </form>
    )
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators( { fetchWeather }, dispatch);
}

export default connect( null, mapDispatchToProps)(SearchBar);
